package com.jeff.utils;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.util.Log;

/**
 * author：duff
 * version：1.0.0
 * date：2017/9/14
 * desc：
 */
public class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
    private MediaScannerConnection mMediaScannerConnection = null;
    private String[] mFilePath;
    private String[] mMimeTypes;
    private int scanTimes = 0;

    public MediaScanner(Context context) {
        mMediaScannerConnection = new MediaScannerConnection(context.getApplicationContext(), this);
    }

    public void scan(String[] filePaths, String[] mimeTypes) {
        if (ArrayUtil.isEmpty(filePaths) || ArrayUtil.isEmpty(mimeTypes) || filePaths.length != mimeTypes.length) {
            Log.d("MediaScanner", "Params is invalidate !");
            return;
        }
        mFilePath = filePaths;
        mMimeTypes = mimeTypes;
        mMediaScannerConnection.connect();
    }

    @Override
    public void onMediaScannerConnected() {
        for (int i = 0; i < mFilePath.length; i++) {
            mMediaScannerConnection.scanFile(mFilePath[i], mMimeTypes[i]);
        }
    }

    @Override
    public void onScanCompleted(String path, Uri uri) {
        scanTimes++;
        if (scanTimes == mFilePath.length) {
            mMediaScannerConnection.disconnect();
            mFilePath = null;
            mMimeTypes = null;
            scanTimes = 0;
        }
    }

}
